/*
 * Copyright 2013 JROSE
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jrose.core.util;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.util.ArrayList;
import java.util.List;

/**
 * XML related utilities.
 *
 * @author Xiaohai Zhang
 * @since 2013-08-25 01:36
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
abstract public class XMLUtils {
    @Getter private static final DocumentBuilder documentBuilder;

    static {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);
            documentBuilder = factory.newDocumentBuilder();
        } catch (ParserConfigurationException ex) {
            throw new RuntimeException(ex.getMessage(), ex);
        }
    }

    public static Element getSingleChildElement(Element parent, String name) {
        NodeList nodeList = parent.getElementsByTagName(name);
        return nodeList.getLength() == 0 ? null : (Element) nodeList.item(0);
    }

    public static List<Element> getChildElements(Element parent, String name) {
        NodeList nodeList = parent.getElementsByTagName(name);
        List<Element> elements = new ArrayList<>(nodeList.getLength());
        for (int i = 0; i < nodeList.getLength(); i++) {
            elements.add((Element) nodeList.item(i));
        }
        return elements;
    }

    public static String getChildElementText(Element parent, String name) {
        Element child = getSingleChildElement(parent, name);
        if (child == null) {
            return null;
        }
        String textContent = child.getTextContent();
        return textContent == null ? null : textContent.trim();
    }
}
